package com.np.storage_demo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileActivity extends AppCompatActivity {

    public static final String FILE_NAME = "tempfile.tmp";
    private Button btnSave;
    private EditText txtContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        btnSave = findViewById(R.id.btn_save);
        txtContent = findViewById(R.id.txt_content);

        try {
            File file = new File(this.getFilesDir().getAbsolutePath() + "/" + FILE_NAME);
            if (file.exists()) {
                InputStream is = openFileInput(FILE_NAME);
                InputStreamReader reader = new InputStreamReader(is, "UTF-8");
                BufferedReader br = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                txtContent.setText(sb.toString());
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        btnSave.setOnClickListener(v -> {
            String content = txtContent.getText().toString();
            try {
                // /data/user/0/com.np.storage_demo1/files/tempfile.tmp
                FileOutputStream os = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                byte[] bytes = content.getBytes();
                os.write(bytes);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }
}